package high.concurrent.controller;


import high.concurrent.dto.NewUserDTO;
import high.concurrent.enums.CouponCategoryEnum;
import high.concurrent.service.CouponService;
import high.concurrent.utils.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  优惠券控制器
 * </p>
 *
 * @author 黄保泽
 * @since 2021-07-17
 */
@Api(tags = "优惠券模块")
@RestController
@RequestMapping("/api/coupon/v1")
@Slf4j
public class CouponController {

    @Autowired
    private CouponService couponService;

    /**
     * 查询所有已发布并且促销的优惠券
     * @param page  当前页
     * @param size  每页条数
     * @return
     */
    @ApiOperation("查询所有优惠券")
    @GetMapping("selectPublicsPromotionCouponList")
    public JsonData selectPublicsPromotionCouponList(@ApiParam("当前页") @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                     @ApiParam("每页条数") @RequestParam(value = "size", defaultValue = "5") Integer size){

        JsonData jsonData = couponService.selectPublicsPromotionCouponList(page, size);
        return jsonData;
    }


    /**
     * 领取优惠券
     * 1. 获取优惠券是否存在(条件是id, 优惠券类型是否是促销， 优惠券是否发布)
     * 2. 校验优惠券是否可以领取： 时间， 库存， 超过限制
     * 3. 扣减库存
     * 4. 保存领券记录
     * @param couponId  优惠券id
     * @return
     */
    @ApiOperation("领取优惠券(促销类型)")
    @PostMapping("receiveCoupon")
    public JsonData receiveCoupon(@ApiParam(value = "优惠券ID", required = true) @RequestParam(value = "coupon_id") Long couponId){

        JsonData jsonData = couponService.receiveCoupon(couponId, CouponCategoryEnum.PROMOTION);
        return jsonData;
    }


    /**
     * 新用户注册发放优惠券
     * 1. 查询新人注册可以发放的所有优惠券
     * 2. 构造ThreadLocal
     * 3. 循环查询的优惠券，逐个添加
     * @param newUserDTO  用户信息
     * @return
     */
    @ApiOperation("领取优惠券(新人注册类型)")
    @PostMapping("RPCNewCouponRecord")
    public JsonData RPCNewCouponRecord(@ApiParam(value = "用户信息", required = true) @RequestBody NewUserDTO newUserDTO){

        JsonData jsonData = couponService.RPCNewCouponRecord(newUserDTO, CouponCategoryEnum.NEW_USER);
        return jsonData;
    }
}

